#include "MessageBox.h"
#include "qthread.h"
#include "view/mainwindow.h"
#include <QApplication>
#include <QDateTime>
#include <QFile>
#include <QTextCodec>
#include "models/databasemanager.h"
//#ifndef QT_DEBUG
#include "log4qt/logger.h"
#include "log4qt/basicconfigurator.h"
#include "log4qt/propertyconfigurator.h"
#include "log4qt/logmanager.h"
#include <log4qt/consoleappender.h>
#include <log4qt/patternlayout.h>
#include <log4qt/rollingfileappender.h>
#include "public/public.h"


using namespace Log4Qt;


#include <QDir>
#include <QSslSocket>
#include <QWebEngineSettings>
#define CENTRE_NUM 32767
#include <qt_windows.h>
#include<Windows.h>
#include<DbgHelp.h>
#pragma comment(lib, "user32.lib")
#pragma comment(lib, "dbghelp.lib")


void GetExceptionDescription(DWORD errCode,QString& err)
{


    //    errCode = 0xc0000005;
    LPTSTR lpMsgBuf = NULL;
    HMODULE Hand = LoadLibrary(TEXT("ntdll.dll"));
    FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
                  FORMAT_MESSAGE_IGNORE_INSERTS/*FORMAT_MESSAGE_FROM_SYSTEM*/|
                  FORMAT_MESSAGE_FROM_HMODULE,
                  Hand,
                  errCode,
                  MAKELANGID(LANG_NEUTRAL,SUBLANG_DEFAULT),
                  (LPTSTR)&lpMsgBuf,
                  0,NULL);
    err = QString::fromWCharArray( lpMsgBuf );
    qDebug()<<err;
    LocalFree(lpMsgBuf);

}


LONG ApplicationCrashHandler(EXCEPTION_POINTERS *pException){//程式异常捕获
    /*
   ***保存数据代码***
 */
    //创建 Dump 文件
    qDebug()<<"触发异常!";
    QString createPath = QCoreApplication::applicationDirPath()+"/Dumps";
    QDir dir;
    dir.mkpath(createPath);
    createPath=QString("%1/dump_%2.dmp").arg(createPath).arg(QDateTime::currentDateTime().toString("yyyy_MM_dd_hh_mm_ss_zzz"));
    std::wstring wlpstr = createPath.toStdWString();
    LPCWSTR lpcwStr = wlpstr.c_str();

    HANDLE hDumpFile = CreateFile(lpcwStr,
                                  GENERIC_WRITE,
                                  0,
                                  NULL,
                                  CREATE_ALWAYS,
                                  FILE_ATTRIBUTE_NORMAL,
                                  NULL);
    if( hDumpFile != INVALID_HANDLE_VALUE){
        //Dump信息
        MINIDUMP_EXCEPTION_INFORMATION dumpInfo;
        dumpInfo.ExceptionPointers = pException;
        dumpInfo.ThreadId = GetCurrentThreadId();
        dumpInfo.ClientPointers = FALSE;
        //写入Dump文件内容
        MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), hDumpFile, MiniDumpNormal, &dumpInfo, NULL, NULL);
    }
    //这里弹出一个错误对话框并退出程序
    EXCEPTION_RECORD* record = pException->ExceptionRecord;
    QString errCode(QString::number(record->ExceptionCode,16)),errAdr(QString::number((UINT)((UINT_PTR)record->ExceptionAddress),16));;
    QString errstr;
    GetExceptionDescription(record->ExceptionCode,errstr);
    if(record->NumberParameters>0){
        if(record->ExceptionInformation[0]==0){
            errstr+="\r\n访问冲突,线程试图读取不可访问的数据";
        }else if(record->ExceptionInformation[0]==1){
            errstr+="\r\n访问冲突,线程尝试写入不可访问的地址";
        }
    }
    QMessageBox::critical(NULL,"程式崩溃","<FONT size=4><div><b>程式崩溃</b><br/></div>"+
                          QString("<div>错误代码：%1</div><div>错误地址：%2</div><div>具体原因：%3</div></FONT>").arg(errCode).arg(errAdr).arg(errstr),
                          QMessageBox::Ok);
    return EXCEPTION_EXECUTE_HANDLER;
}
int main(int argc, char *argv[])
{
    //qputenv("QT_ENABLE_HIGHDPI_SCALING", "1");
    //QGuiApplication::setHighDpiScaleFactorRoundingPolicy(Qt::HighDpiScaleFactorRoundingPolicy::PassThrough);
    QApplication::setAttribute(Qt::AA_DisableHighDpiScaling);
    QApplication a(argc, argv);
    QWebEngineSettings::defaultSettings()->setAttribute(QWebEngineSettings::PluginsEnabled, true);
    SetUnhandledExceptionFilter((LPTOP_LEVEL_EXCEPTION_FILTER)ApplicationCrashHandler);//注冊异常捕获函数

    //创建出log目录，否则配置会失败
    getLogPath();
    PropertyConfigurator::configure(":/Log4qt.properties");
    QList<Appender *> appenders = Log4Qt::LogManager::rootLogger()->appenders();
    for (QList<Appender *>::Iterator it = appenders.begin(); it != appenders.end(); ++it)
    {
        if ((*it)->name() == "file")
        {
            RollingFileAppender *fileAppender = static_cast<RollingFileAppender *>(*it);

            // 设置日志文件路径
            fileAppender->setFile(getLogPath() + QDateTime::currentDateTime().toString("yyyyMMdd_hhmm") + ".log");

            // ✅ 关键：设置文件编码为 UTF-8，防止中文乱码
            fileAppender->setEncoding(QTextCodec::codecForName("UTF-8"));

            // 激活选项（必须放在最后）
            fileAppender->activateOptions();
        }
    }
#ifdef QT_DEBUG
    // Debug 版本，不捕获 Qt 消息
#else
    // Release 版本，捕获 Qt 消息
    Log4Qt::LogManager::setHandleQtMessages(true);
#endif

    qInfo()<<"程序启动";

    // 初始化数据库
    if (!DatabaseManager::getInstance()->initDatabase()) {
        warning(NULL,QObject::tr("数据库初始化失败"));
        return -1;
        // 处理错误...
    }
    MainWindow::getInstance()->setWindowTitle("HumanRobot");
    MainWindow::getInstance()->show();



    int result = a.exec();

    // 确保在应用退出前完全清理资源
    MainWindow::getInstance()->Release();

    // 强制处理所有待处理的事件
    QCoreApplication::processEvents();
    QCoreApplication::sendPostedEvents(nullptr, QEvent::DeferredDelete);

    qInfo()<<"程序退出";
    QCoreApplication::setApplicationVersion(APP_VERSION);
    qDebug() <<"版本号"<< APP_VERSION;

    return result;
}
